package org.budo.canal.meta;

import org.budo.support.spring.util.SpringUtil;
import org.springframework.beans.factory.FactoryBean;

import com.alibaba.otter.canal.common.zookeeper.ZkClientx;
import com.alibaba.otter.canal.meta.CanalMetaManager;
import com.alibaba.otter.canal.meta.MemoryMetaManager;
import com.alibaba.otter.canal.meta.ZooKeeperMetaManager;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 会自己去IOC里找ZkClientx，如果没有就Memory
 * 
 * @author limingwei
 */
@Getter
@Setter
@Slf4j
public class MetaManagerFactoryBean implements FactoryBean<CanalMetaManager> {
    private ZkClientx zkClientx;

    @Override
    public CanalMetaManager getObject() throws Exception {
        if (null == this.zkClientx()) {
            log.error("#24 zkClientx is null, return MemoryMetaManager, this=" + this);
            return new MemoryMetaManager();
        }

        ZooKeeperMetaManager zooKeeperMetaManager = new ZooKeeperMetaManager();
        zooKeeperMetaManager.setZkClientx(this.zkClientx());
        return zooKeeperMetaManager;
    }

    private ZkClientx zkClientx() {
        if (null != this.getZkClientx()) {
            return this.getZkClientx();
        }

        return SpringUtil.getBean(ZkClientx.class);
    }

    @Override
    public Class<?> getObjectType() {
        return CanalMetaManager.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}